package com.advertisementsystem.Servie.Impl;

import com.advertisementsystem.Dto.DeviceDTO;
import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.Mapper.DeviceMapper;
import com.advertisementsystem.Servie.AmapService;
import com.advertisementsystem.Servie.DeviceService;
import com.advertisementsystem.entity.Device;
import com.advertisementsystem.vo.GeoResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private AmapService amapService;
    @Override
    public void createDevice(DeviceDTO dto) {
        // 获取当前用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        // 检查设备编号是否已存在
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getDeviceCode, dto.getDeviceCode());
        if (deviceMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("设备编号已存在");
        }

        // 创建设备
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setOwnerId(loginUser.getUser().getId());
        device.setStatus(1); // 启用状态
        device.setCreatedTime(LocalDateTime.now());
        device.setUpdatedTime(LocalDateTime.now());

        // 处理位置数据
        // 情况1：只有地址，没有经纬度 - 地址转经纬度
        if (StringUtils.isNotBlank(device.getLocation()) &&
                (device.getLatitude() == null || device.getLongitude() == null)) {
            GeoResult geo = amapService.getGeoCode(device.getLocation());
            if (geo != null) {
                device.setLatitude(geo.getLatitude());
                device.setLongitude(geo.getLongitude());
            }
        }
        // 情况2：有经纬度，没有地址 - 经纬度转地址
        else if (StringUtils.isBlank(device.getLocation()) &&
                device.getLatitude() != null && device.getLongitude() != null) {
            String address = amapService.getAddressByLocation(device.getLongitude(), device.getLatitude());
            if (StringUtils.isNotBlank(address)) {
                device.setLocation(address);
            }
        }
        // 情况3：都有，保持原样

        deviceMapper.insert(device);
    }

    @Override
    public void updateDevice(Long id, DeviceDTO dto) {
        // 检查设备是否存在
        Device device = deviceMapper.selectById(id);
        if (device == null) {
            throw new RuntimeException("设备不存在");
        }

        // 检查权限
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        if (!device.getOwnerId().equals(loginUser.getUser().getId())&&!loginUser.getPermissions().contains("ROLE_ADMIN")) {
            throw new RuntimeException("无权修改此设备");
        }

        // 检查设备编号是否重复
        if (!device.getDeviceCode().equals(dto.getDeviceCode())) {
            LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Device::getDeviceCode, dto.getDeviceCode());
            if (deviceMapper.selectCount(wrapper) > 0) {
                throw new RuntimeException("设备编号已存在");
            }
        }

        // 更新设备
        BeanUtils.copyProperties(dto, device);
        device.setUpdatedTime(LocalDateTime.now());
        deviceMapper.updateById(device);
    }

    @Override
    public void deleteDevice(Long id) {
        // 检查设备是否存在
        Device device = deviceMapper.selectById(id);
        if (device == null) {
            throw new RuntimeException("设备不存在");
        }

        // 检查权限
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        if (!device.getOwnerId().equals(loginUser.getUser().getId())&&!loginUser.getPermissions().contains("ROLE_ADMIN")) {
            throw new RuntimeException("无权删除此设备");
        }

        deviceMapper.deleteById(id);
    }

    @Override
    public Page<Device> getDeviceList(Integer pageNum, Integer pageSize,String name,Integer status,String keyword,String type) {
        log.info("getDeviceList:{},{},{},{},{},{}",pageNum,pageSize,name,status,keyword,type);
        Page<Device> page = new Page<>(pageNum, pageSize);

        // 获取当前用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        // 构建查询条件
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();

        if (name != null)
        {
            wrapper.like(Device::getName, name);
        }
        if (status != null)
        {
            wrapper.eq(Device::getStatus, status);
        }
        // 关键词搜索（设备名称或编号）
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.and(w -> w.like(Device::getName, keyword)
                    .or()
                    .like(Device::getDeviceCode, keyword));
        }
        if (StringUtils.isNotBlank(type))
        {
            wrapper.eq(Device::getType, type);
        }

        // wrapper.eq(Device::getStatus, status);
        // 如果是设备拥有者，只能看到自己的设备
        if (loginUser.getPermissions().contains("ROLE_DEVICE_OWNER")) {
            wrapper.eq(Device::getOwnerId, loginUser.getUser().getId());
            log.info("设备");
        }

        wrapper.orderByDesc(Device::getCreatedTime);

        Page<Device> result =deviceMapper.selectPage(page, wrapper);

        log.info("getDeviceList:{}",result);
        return result;
    }

    @Override
    public Device getDeviceDetail(Long id) {
        Device l = deviceMapper.selectById(id);
        log.info("getDeviceDetail:{}",l);
        return l;
    }

    @Override
    public void enableDevice(Long id) {
        Device device = deviceMapper.selectById(id);
        if (device == null) {
            throw new RuntimeException("设备不存在");
        }

        device.setStatus(1);
        device.setUpdatedTime(LocalDateTime.now());
        deviceMapper.updateById(device);
    }

    @Override
    public void disableDevice(Long id) {
        Device device = deviceMapper.selectById(id);
        if (device == null) {
            throw new RuntimeException("设备不存在");
        }

        device.setStatus(0);
        device.setUpdatedTime(LocalDateTime.now());
        deviceMapper.updateById(device);
    }
}